/**
 * @Author: lena
 * @Description:udp客户端
 * @Version: 1.0.0
 * @Date: 2021/9/11 14:27
 */

package udp

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func Client1() {
	// 监听端口
	conn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(127, 0, 0, 1),
		Port: 20000,
	})
	if err != nil {
		fmt.Println("[client]listen err :", err)
		return
	}
	defer conn.Close()

	// 直接可以收发数据
	var data [1024]byte
	reader := bufio.NewReader(os.Stdin)
	for {
		// 接收数据 : func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
		n, addr, err := conn.ReadFromUDP(data[:])
		if err != nil {
			fmt.Println("[client]receive err :", err)
			break
		}
		fmt.Println("[client]接收到信息:", string(data[:n]))
		// 回复 => 发送数据
		fmt.Printf("[client]请输入要回复的信息：")
		//var reply string
		///fmt.Scanln(&reply)
		reply, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("[client]read input err :", err)
			break
		}
		conn.WriteToUDP([]byte(reply), addr)
	}

}
